/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package botsim;

import com.ardor3d.framework.Scene;
import com.ardor3d.intersection.PickResults;
import com.ardor3d.math.Ray3;
import com.ardor3d.math.type.ReadOnlyColorRGBA;
import com.ardor3d.math.type.ReadOnlyVector3;
import com.ardor3d.renderer.Renderer;
import com.ardor3d.scenegraph.Line;
import com.ardor3d.scenegraph.Renderable;
import com.bulletphysics.dynamics.DynamicsWorld;
import com.bulletphysics.linearmath.DebugDrawModes;
import com.bulletphysics.linearmath.IDebugDraw;
import javax.vecmath.Vector3f;

/**
 * Debug scene drawing code for bullet.
 * @author Prasanna Velagapudi <pkv@cs.cmu.edu>
 */
public class BulletScene implements Scene {
    DynamicsWorld _world;
    ArdorDebugDraw _drawer;
    
    public BulletScene(DynamicsWorld world) {
        _drawer = new ArdorDebugDraw();

        _world = world;
        _world.setDebugDrawer(_drawer);
    }

    public void update(float time) {
        _world.stepSimulation(time, 10, 0.016f);
    }

    public boolean renderUnto(Renderer renderer) {
        _drawer.setRenderer(renderer);
        _world.debugDrawWorld();
        return true;
    }

    public PickResults doPick(Ray3 pickRay) {
        return null;
    }

    private class ArdorDebugDraw extends IDebugDraw {
        Renderer _renderer = null;
        int _index = 0;

        public void setRenderer(Renderer renderer) {
            _renderer = renderer;
        }

        public String nextId() {
            return "Obj" + (_index++);
        }

        @Override
        public void drawLine(Vector3f from, Vector3f to, Vector3f color) {
            ReadOnlyVector3[] vertices = new ReadOnlyVector3[] {
                ArdorBulletUtil.toArdorVector3(from),
                ArdorBulletUtil.toArdorVector3(to)
            };

            ReadOnlyColorRGBA[] colors = new ReadOnlyColorRGBA[] {
                ArdorBulletUtil.toArdorColorRGBA(color),
                ArdorBulletUtil.toArdorColorRGBA(color)
            };

            _renderer.draw((Renderable)(new Line(nextId(), vertices, null, colors, null)));
        }

        @Override
        public void drawContactPoint(Vector3f PointOnB, Vector3f normalOnB, float distance, int lifeTime, Vector3f color) {
            
        }

        @Override
        public void reportErrorWarning(String warningString) {
            System.err.println(warningString);
        }

        @Override
        public void draw3dText(Vector3f location, String textString) {
            
        }

        @Override
        public void setDebugMode(int debugMode) {
            
        }

        @Override
        public int getDebugMode() {
            return DebugDrawModes.DRAW_WIREFRAME | DebugDrawModes.DRAW_AABB;
        }
    }
}
